<template>
  <div class="work-order-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="工单类型">
          <el-select v-model="queryParams.type" placeholder="请选择工单类型" clearable>
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select v-model="queryParams.status" placeholder="请选择工单状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="售货机">
          <el-select v-model="queryParams.machineId" placeholder="请选择售货机" clearable>
            <el-option
              v-for="machine in machineList"
              :key="machine.id"
              :label="machine.name"
              :value="machine.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工单列表 -->
    <el-table
      v-loading="loading"
      :data="workOrderList"
      border
      style="width: 100%"
    >
      <el-table-column prop="type" label="工单类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeType(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="工单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="machineName" label="售货机" />
      <el-table-column prop="assigneeName" label="处理人" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link @click="handleStatus(row, 'PROCESSING')" v-if="row.status === 'PENDING'">
            处理
          </el-button>
          <el-button type="success" link @click="handleStatus(row, 'COMPLETED')" v-if="row.status === 'PROCESSING'">
            完成
          </el-button>
          <el-button type="warning" link @click="handleAssign(row)" v-if="row.status === 'PENDING'">
            分配
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 工单表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="workOrderFormRef"
        :model="workOrderForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="workOrderForm.type" placeholder="请选择工单类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="售货机" prop="machineId">
          <el-select v-model="workOrderForm.machineId" placeholder="请选择售货机">
            <el-option
              v-for="machine in machineList"
              :key="machine.id"
              :label="machine.name"
              :value="machine.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="productId" v-if="workOrderForm.type === 'RESTOCK'">
          <el-select v-model="workOrderForm.productId" placeholder="请选择商品">
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="assigneeId">
          <el-select v-model="workOrderForm.assigneeId" placeholder="请选择处理人">
            <el-option
              v-for="maintainer in maintainerList"
              :key="maintainer.id"
              :label="maintainer.name"
              :value="maintainer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="workOrderForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入工单描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配工单对话框 -->
    <el-dialog
      title="分配工单"
      v-model="assignDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        label-width="80px"
      >
        <el-form-item label="处理人" prop="assigneeId">
          <el-select v-model="assignForm.assigneeId" placeholder="请选择处理人">
            <el-option
              v-for="maintainer in maintainerList"
              :key="maintainer.id"
              :label="maintainer.name"
              :value="maintainer.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWorkOrderList, addWorkOrder, updateWorkOrder, deleteWorkOrder, updateWorkOrderStatus, assignWorkOrder } from '@/api/workOrder'
import { getMachineList } from '@/api/machine'
import { getProductList } from '@/api/product'
import { getMaintainerList } from '@/api/user'

// 工单类型选项
const typeOptions = [
  { label: '安装', value: 'INSTALL' },
  { label: '补货', value: 'RESTOCK' },
  { label: '维修', value: 'REPAIR' }
]

// 工单状态选项
const statusOptions = [
  { label: '待处理', value: 'PENDING' },
  { label: '处理中', value: 'PROCESSING' },
  { label: '已完成', value: 'COMPLETED' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  machineId: undefined
})

// 列表数据
const loading = ref(false)
const workOrderList = ref([])
const total = ref(0)
const machineList = ref([])
const productList = ref([])
const maintainerList = ref([])

// 获取工单列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getWorkOrderList(queryParams)
    workOrderList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取工单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取售货机列表
const getMachines = async () => {
  try {
    const { data } = await getMachineList()
    machineList.value = data
  } catch (error) {
    console.error('获取售货机列表失败:', error)
  }
}

// 获取商品列表
const getProducts = async () => {
  try {
    const { data } = await getProductList()
    productList.value = data
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取维护人员列表
const getMaintainers = async () => {
  try {
    const { data } = await getMaintainerList()
    maintainerList.value = data
  } catch (error) {
    console.error('获取维护人员列表失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.type = undefined
  queryParams.status = undefined
  queryParams.machineId = undefined
  handleQuery()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('') // add 或 edit
const dialogTitle = ref('')
const workOrderFormRef = ref()
const workOrderForm = reactive({
  id: undefined,
  type: undefined,
  machineId: undefined,
  productId: undefined,
  assigneeId: undefined,
  description: ''
})

// 表单校验规则
const rules = {
  type: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  machineId: [
    { required: true, message: '请选择售货机', trigger: 'change' }
  ],
  productId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  assigneeId: [
    { required: true, message: '请选择处理人', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入工单描述', trigger: 'blur' }
  ]
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增工单'
  dialogVisible.value = true
  workOrderForm.id = undefined
  workOrderForm.type = undefined
  workOrderForm.machineId = undefined
  workOrderForm.productId = undefined
  workOrderForm.assigneeId = undefined
  workOrderForm.description = ''
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑工单'
  dialogVisible.value = true
  workOrderForm.id = row.id
  workOrderForm.type = row.type
  workOrderForm.machineId = row.machineId
  workOrderForm.productId = row.productId
  workOrderForm.assigneeId = row.assigneeId
  workOrderForm.description = row.description
}

// 提交表单
const submitForm = async () => {
  if (!workOrderFormRef.value) return
  
  await workOrderFormRef.value.validate()
  
  try {
    if (dialogType.value === 'add') {
      await addWorkOrder(workOrderForm)
      ElMessage.success('新增成功')
    } else {
      await updateWorkOrder(workOrderForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存工单失败:', error)
  }
}

// 更新状态
const handleStatus = (row, status) => {
  const statusMap = {
    'PROCESSING': '开始处理',
    'COMPLETED': '完成'
  }
  
  ElMessageBox.confirm(
    `确认${statusMap[status]}工单吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateWorkOrderStatus(row.id, status)
      ElMessage.success(`${statusMap[status]}成功`)
      getList()
    } catch (error) {
      console.error('更新状态失败:', error)
    }
  })
}

// 分配工单相关
const assignDialogVisible = ref(false)
const assignFormRef = ref()
const assignForm = reactive({
  id: undefined,
  assigneeId: undefined
})

const assignRules = {
  assigneeId: [
    { required: true, message: '请选择处理人', trigger: 'change' }
  ]
}

// 分配按钮点击
const handleAssign = (row) => {
  assignDialogVisible.value = true
  assignForm.id = row.id
  assignForm.assigneeId = row.assigneeId
}

// 提交分配
const submitAssign = async () => {
  if (!assignFormRef.value) return
  
  await assignFormRef.value.validate()
  
  try {
    await assignWorkOrder(assignForm.id, assignForm.assigneeId)
    ElMessage.success('分配成功')
    assignDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('分配工单失败:', error)
  }
}

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该工单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteWorkOrder(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除工单失败:', error)
    }
  })
}

// 获取工单类型标签类型
const getTypeType = (type) => {
  const map = {
    'INSTALL': '',
    'RESTOCK': 'success',
    'REPAIR': 'warning'
  }
  return map[type] || ''
}

// 获取工单类型标签文本
const getTypeLabel = (type) => {
  const option = typeOptions.find(item => item.value === type)
  return option ? option.label : type
}

// 获取工单状态标签类型
const getStatusType = (status) => {
  const map = {
    'PENDING': 'info',
    'PROCESSING': 'warning',
    'COMPLETED': 'success'
  }
  return map[status] || ''
}

// 获取工单状态标签文本
const getStatusLabel = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : status
}

onMounted(() => {
  getList()
  getMachines()
  getProducts()
  getMaintainers()
})
</script>

<style scoped>
.work-order-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.form-inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style> 